<template>
	<div class='app-container'>
		<el-form class="filter-container" label-position="left" label-width="68px">
			<el-row :gutter="24">
				<el-col :span="4">
					<el-form-item label="专题名称" style="margin-bottom: 0!important;">
						<el-input @keyup.enter.native="getList" class="filter-item" placeholder="请输入名称" v-model.trim="listQuery.seminarName"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="审核状态" style="margin-bottom: 0!important;">
						<el-select clearable v-model="listQuery.auditStatus" placeholder="请选择">
							<el-option value="" label="全部"></el-option>
							<el-option value="0" label="未审核"></el-option>
							<el-option value="1" label="已审核"></el-option>
							<el-option value="2" label="已驳回"></el-option>
							<el-option value="3" label="已部分审核"></el-option>
							<el-option value="4" label="已部分驳回"></el-option>
							<el-option value="5" label="已下线"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="更新时间" style="margin-bottom: 0!important;">
						<el-date-picker type="datetimerange" :default-time="['00:00:00', '23:59:59']" @keyup.enter.native="getList" class="filter-item" align="right" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" v-model="time" :picker-options="pickerOptions">
						</el-date-picker>
					</el-form-item>
				</el-col>
				<el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList">{{$t('table.search')}}</el-button>
				<el-button :loading="refreshing" class="filter-item el-icon-refresh" style="margin-left: 10px;" @click="refreshList" type="primary">&nbsp;刷新列表</el-button>
				<el-button class="filter-item" @click="newProject()" type="success" icon="el-icon-plus">新增</el-button>
			</el-row>
		</el-form>
		<el-table stripe :data="tableData" v-loading="listLoading" element-loading-text="加载中..." border fit highlight-current-row style="width: 100%">
			<el-table-column align="center" label="专题名称" min-width="150">
				<template slot-scope="scope">
					<el-button class="preview-button" type="text" @click="handleShow(scope.row, 'show')">{{scope.row.seminarName}}</el-button>
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" align="center" width="100"></el-table-column>
			<el-table-column prop="updateTime" label="更新时间" align="center" width="100"></el-table-column>
			<el-table-column prop="type" label="专题类型" align="center">
				<template slot-scope="scope">
					<span v-if="scope.row.type == 0">人工专题</span>
					<span v-else>智能专题</span>
				</template>
			</el-table-column>
			<el-table-column align="center" label="审核状态" min-width="80">
				<template slot-scope="scope">
					<el-tag size="small" :type="checkClass(scope.row.auditStatus)">{{checkStatu(scope.row.auditStatus)}}</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="updater" label="审核人" align="center"></el-table-column>
			<el-table-column prop="adjustDesc" label="驳回原因" align="center" min-width="200"></el-table-column>
			<el-table-column prop="topTime" label="置顶时间" align="center" width="100"></el-table-column>
			<el-table-column label="操作" align="center" min-width="100">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleShow(scope.row, 'update')">编辑</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="pagination-container">
			<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
		</div>
		<el-dialog :fullscreen='true' :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
			<el-form ref="temp" :model="temp" :rules="editRules" label-position="left" label-width="80px" style='margin: auto; max-width: 1200px'>
				<el-row :gutter="24">
					<el-col :span="12">
						<el-form-item label="专题名称" prop="seminarName">
							<el-input v-model.trim="temp.seminarName" type="text" placeholder="请输入" :disabled="dialogStatus == 'show'" :maxlength='50'></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="专题类型" prop="type">
							<el-select v-model="temp.type" placeholder="请选择" :disabled="dialogStatus == 'show'">
								<el-option label="人工专题" :value='0'></el-option>
								<!-- <el-option label="智能专题" :value='1'></el-option> -->
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="置顶时间" prop="topTime">
							<el-date-picker v-model="temp.topTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" :disabled="dialogStatus == 'show'"></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="专题描述" prop="descript">
							<el-input v-model="temp.descript" type="textarea" :rows="3" :maxlength='200' placeholder="请输入" :disabled="dialogStatus == 'show'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="专题资讯" prop="news">
							<div style="float: right;" v-if="dialogStatus !== 'show'">
								<el-button @click="addNews()" type="text">新增</el-button>
								<el-button @click="evtDelete(temp.news)" type="text">删除</el-button>
							</div>
							<el-table v-loading="tagLoading" element-loading-text="加载中..." stripe max-height="500" :data="temp.news" style="width: 100%" border fit highlight-current-row @selection-change="evtSelect">
								<el-table-column v-if="dialogStatus !== 'show'" align="center" type="selection" width="55" key="1"></el-table-column>
								<el-table-column label="资讯标题" align="center" min-width="150">
									<template slot-scope="scope">
										<el-button class="preview-button" type="text" @click="showInfo(scope.row)">{{ scope.row.title }}</el-button>
									</template>
								</el-table-column>
								<el-table-column prop="summary" label="资讯摘要" align="center" show-overflow-tooltip min-width="150"></el-table-column>
								<el-table-column prop="update_time" label="更新时间" align="center" width="100"></el-table-column>
								<el-table-column align="center" label="资讯状态" min-width="80">
									<template slot-scope="scope">
										<el-tag size="small" :type="checkNews(scope.row.news_status)">{{checkNewsStatu(scope.row.news_status)}}</el-tag>
									</template>
								</el-table-column>
								<el-table-column prop="is_original" label="资讯类型" align="center">
									<template slot-scope="scope">
										<span v-if="scope.row.is_original == 0">原创资讯</span>
										<span v-else-if="scope.row.is_original == 1">智能资讯</span>
										<span v-else>机器写稿</span>
									</template>
								</el-table-column>
								<el-table-column label="操作" align="center" width="150" v-if="dialogStatus !== 'show'" key="2">
									<template slot-scope="scope">
										<el-button size="mini" type="danger" @click="deleteRow(scope.$index, temp.news)">删除</el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-form-item>
						<el-dialog title="插入资讯" :visible.sync="dialogGetNews" width="50%" append-to-body :close-on-click-modal=false>
							<div v-if='dialogGetNews'>
								<searchNews @getMethod='getMethod' @closeDio='closeDio'></searchNews>
							</div>
						</el-dialog>
					</el-col>
					<el-col :span="12">
						<el-form-item label="专题配图" prop="picUrl" v-if="dialogStatus !== 'show'">
							<el-upload 
								:action='imageUploadUrl' 
								:headers="{Authorization: 'Bearer ' + $store.getters.token}" 
								list-type="picture-card" 
								:limit="1" 
								:on-exceed="handleExceed"
								:before-upload="beforeUpload"
								:on-preview="handlePictureCardPreview" 
								:on-remove="handlePictureCardRemove" 
								:on-success="handleSuccessCallback" 
								:on-error="handleErrorCallback" 
								:file-list="pictureList">
								<i class="el-icon-plus"></i>
								<div slot="tip" class="el-upload__tip" style="line-height: 16px;">只能上传图片文件，且不超过1M</div>
							</el-upload>
							<el-dialog :visible.sync="dialogVisible" append-to-body>
								<img width="100%" :src="temp.picUrl" alt="">
							</el-dialog>
						</el-form-item>
						<el-form-item v-if="dialogStatus =='show'" label="专题配图" prop="picUrl">
							<img :src="temp.picUrl" class="avatar">
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="success" @click="auditMethod('temp')" v-if="dialogStatus !== 'show'">发布专题</el-button>
				<el-button type="primary" @click="dialogFormVisible = false">关闭</el-button>
			</div>
			<el-dialog append-to-body :fullscreen='true' :title="infoTitle" :visible.sync="dialogInfo">
				<div v-if='dialogInfo'>
					<component :is="currentView" :infoMsg='infoMsg' @closeFile='closeFile'></component>
					<!--<newsPreview :infoMsg='infoMsg' @closeFile='closeFile'></newsPreview>-->
				</div>
			</el-dialog>
		</el-dialog>
	</div>
</template>

<script>
	import { getPageList, getEdit, addInfo, publish, originalUploadUrl } from '@/api/project'
	import pinyin from 'pinyin'
	import searchNews from './searchNews'
	import intellPreview from './intellPreview'
	import origPreview from './origPreview'
	import roboPreview from './roboPreview'

	export default {
		name: 'myProject',
		components: {
			searchNews,
			intellPreview,
			origPreview,
			roboPreview
		},
		created() {
			this.getList()
		},
		methods: {
			getList() {
				this.listLoading = true
				if(this.time) {
					this.listQuery.startTime = this.time[0]
					this.listQuery.endTime = this.time[1]
				} else {
					this.listQuery.startTime = ''
					this.listQuery.endTime = ''
				}
				getPageList(this.listQuery).then(res => {
					this.tableData = res.Data
					this.total = res.total * 1
					this.listLoading = false
				})
			},
			handleSizeChange(val) {
				this.listQuery.pageSize = val
				this.getList()
			},
			handleCurrentChange(val) {
				this.listQuery.pageNum = val
				this.getList()
			},
			newProject() {
				this.temp = {
					descript: '',
					news: [],
					picUrl: '',
					seminarName: '',
					topTime: '',
					type: 0
				}
				this.pictureList = []
				this.dialogStatus = 'create'
				this.dialogFormVisible = true
				this.$nextTick(() => {
					this.$refs['temp'].clearValidate()
				})
			},
			handleShow(row, str) {
				this.tagLoading = true
				getEdit({
					'id': row.id
				}).then(res => {
					let val = res.Data[0]
					this.temp = Object.assign({}, val)
					this.pictureList = [{
						url: val.picUrl
					}]
					this.dialogStatus = str
					this.tagLoading = false
					this.dialogFormVisible = true
					this.$nextTick(() => {
						this.$refs['temp'].clearValidate()
					})
				})
			},
			refreshList() {
				this.refreshing = true
				const params = Object.assign({}, this.listQuery)
				if(this.listQuery.updateTime) {
					params.startUpdateTime = this.listQuery.updateTime[0]
					params.endUpdateTime = this.listQuery.updateTime[1]
				} else {
					params.startUpdateTime = ''
					params.endUpdateTime = ''
				}
				getPageList(params).then(res => {
					this.refreshing = false
					this.tableData = res.Data
					this.total = parseInt(res.total)
					this.$message({
						message: '刷新成功',
						type: 'success'
					})
				}).catch(() => {
					this.refreshing = false
				})
			},
			checkNews(sta) {
				switch(sta) {
					case 0:
						return '' // '待处理'
					case 1:
						return 'success' // '已通过'
					case 2:
						return 'danger' // 2：未通过
				}
			},
			checkNewsStatu(data) {
				switch(data) {
					case 0:
						return '待处理'
					case 1:
						return '已通过'
					case 2:
						return '未通过'
				}
			},
			checkClass(data) {
				switch(data) {
					case 0:
						return '' // '未审核'
					case 1:
						return 'success' // '已审核'
					case 2:
						return 'danger'
					case 3:
						return 'warning'
					case 4:
						return 'warning'
					case 5:
						return 'danger'
				}
			},
			checkStatu(data) {
				switch(data) {
					case 0:
						return '未审核'
					case 1:
						return '已审核'
					case 2:
						return '已驳回'
					case 3:
						return '已部分审核'
					case 4:
						return '已部分驳回'
					case 5:
						return '已下线'
				}
			},
			addNews() {
				this.dialogGetNews = true
			},
			showInfo(row) {
				this.infoMsg = Object.assign({}, row)
				if(row.is_original == 0){
					this.currentView = 'origPreview'
					this.infoTitle = '原创资讯详情'
				}else if(row.is_original == 1){
					this.currentView = 'intellPreview'
					this.infoTitle = '智能资讯详情'
				}else if(row.is_original == 2){
					this.currentView = 'roboPreview'
					this.infoTitle = '机器写稿详情'
				}
				this.dialogInfo = true
			},
			getMethod(news) {
				let arr = news.map(item => {
					item.news_status = 0
					return item
				})
				this.temp.news = this.temp.news.concat(arr)
				this.temp.news = this.temp.news.sort((a,b) => {
					return a.update_time > b.update_time ? -1 : 1;
				})
				this.dialogGetNews = false
			},
			closeDio() {
				this.dialogGetNews = false
			},
			closeFile() {
				this.dialogInfo = false
			},
			evtSelect(val) {
				this.evtSelection = val
			},
			deleteRow(index, rows) {
				this.$confirm('确认删除, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					rows.splice(index, 1);
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					})
				})
			},
			evtDelete(rows) {
				if(this.evtSelection.length) {
					this.$confirm('确认删除，是否继续？', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						this.evtSelection.forEach(item => {
							rows.forEach((val, index) => {
								if(item.news_id == val.news_id) {
									rows.splice(index, 1);
								}
							})
						})
					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消删除'
						})
					})
				} else {
					this.$message({
						type: 'warning',
						message: '请勾选需要删除的资讯'
					})
					return
				}
			},
	      	handleExceed(files, fileList) {
	      		this.$message.warning(`当前限制上传 1个文件`);
      		},
			beforeUpload(file) {
				const isJPG = [
					'image/jpeg',
					'image/svg+xml',
					'image/bmp',
					'image/webp',
					'image/vnd.dwg',
					'image/vnd.dxf',
					'image/gif',
					'image/jp2',
					'image/tiff',
					'image/vnd.svf',
					'image/png'
				].indexOf(file.type) > -1
				const isLt2M = file.size / 1024 / 1024 < 1
				if(!isJPG) {
					this.$message.error('请上传图片文件！')
				}
				if(!isLt2M) {
					this.$message.error('上传文件大小不能超过 1MB!')
				}
				return isJPG && isLt2M
			},
			handlePictureCardPreview(file) {
				this.dialogVisible = true
			},
			handlePictureCardRemove(file, fileList) {
				this.pictureList = fileList
				this.temp.picUrl = ''
			},
			handleSuccessCallback(res, file, fileList) {
				if(res.Meta.Code == 0){
					this.pictureList = [{ name: file.name, url: res.Data[0] }]
					this.temp.picUrl = res.Data[0]
				} else {
					this.pictureList = []
					this.temp.picUrl = ''
					this.$message.error(res.Meta.Message)
				}
			},
			handleErrorCallback(err, file, fileList) {
				this.temp.picUrl = ''
				this.$message.error(err)
			},
			auditMethod(formName) {
				this.$refs[formName].validate(valid => {
					if(valid) {
						if(this.dialogStatus == 'create') {
							const obj = Object.assign({}, this.temp)
							addInfo(obj).then(res => {
								this.getList()
								this.dialogFormVisible = false
								this.$notify({
									title: '成功',
									message: '发布成功',
									type: 'success',
									duration: 5000
								})
							})
						} else if(this.dialogStatus == 'update') {
							const myObj = {
								adjustDesc: "",
								auditStatus: null,
								createTime: "",
								creater: "",
								dataStatus: null,
								descript: "",
								id: '',
								news: [],
								picUrl: "",
								seminarName: "",
								seminarStatus: null,
								topTime: "",
								type: null,
								updateTime: "",
								updater: ""
							}
							Object.keys(myObj).forEach(val => {
								myObj[val] = this.temp[val]
							})
							publish(myObj).then(res => {
								this.getList()
								this.dialogFormVisible = false
								this.$notify({
									title: '成功',
									message: '发布成功',
									type: 'success',
									duration: 5000
								})
							})
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				})
			}
		},
		data() {
			return {
				imageUploadUrl: originalUploadUrl,
				refreshing: false,
				dialogFormVisible: false,
				total: null,
				dialogGetNews: false,
				currentView: 'intellPreview',
				listLoading: false,
				time: ['', ''],
				listQuery: {
					pageNum: 1,
					pageSize: 20,
					auditStatus: '',
					seminarName: '',
					startTime: '',
					endTime: ''
				},
				infoTitle: '',
				dialogInfo: false,
				infoMsg: {},
				evtSelection: [],
				tableData: [],
				pictureList: [],
				temp: {
					descript: '',
					news: [],
					picUrl: '',
					seminarName: '',
					topTime: '',
					type: 0
				},
				tagLoading: false,
				textMap: {
					show: '专题详情',
					update: '编辑专题',
					create: '新增专题'
				},
				editRules: {
					seminarName: [{
						required: true,
						message: '请输入专题名称',
						trigger: 'blur'
					}],
					descript: [{
						required: true,
						message: '请输入专题描述',
						trigger: 'blur'
					}],
					news: [{
						required: true,
						message: '请选择相关资讯',
						trigger: 'change'
					}],
					picUrl: [{
						required: true,
						message: '请选择图片',
						trigger: 'change'
					}]
				},
				dialogStatus: '',
				dialogVisible: false,
				pickerOptions: {
					shortcuts: [{
						text: '今天',
						onClick(picker) {
							const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() -
								1000
							const start = end + 1000 - 3600 * 1000 * 24
							picker.$emit('pick', [start, end])
						}
					}, {
						text: '最近三天',
						onClick(picker) {
							const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() -
								1000
							const start = end + 1000 - 3600 * 1000 * 24 * 3
							picker.$emit('pick', [start, end])
						}
					}, {
						text: '最近一周',
						onClick(picker) {
							const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() -
								1000
							const start = end + 1000 - 3600 * 1000 * 24 * 7
							picker.$emit('pick', [start, end])
						}
					}]
				}
			}
		}
	}
</script>
<style>
	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>